import pyaudio
import wave
#缓冲区帧数， 512 * 精度 * 通道数
CHUNK = 1024
#采样精度 16kbps,2字节大小
FORMAT = pyaudio.paInt16
CHANNELS = 1
# RATE = 44100
RATE = 16000
RECORD_SECONDS = 10
WAVE_OUTPUT_FILENAME = "output1.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
# z=0
# while True:
#     if(z == 3):
#         break
#
#     z += 1
#     for i in range(0, int(RATE / CHUNK)):
        # print(z)

print("* done recording")
print(b''.join(frames).__len__())
stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()